<?php
define('ROOT_PATH',  str_replace('\\', '/', dirname(dirname(dirname(dirname(__FILE__)))))."/");
ini_set('date.timezone','Asia/Shanghai');
// error_reporting(E_ERROR);

require_once(ROOT_PATH."lib/db_init.php");//引入数据库文件
require_once(ROOT_PATH."lib/lib_base.php");
require_once(ROOT_PATH."lib/lib_safe.php");
require_once(ROOT_PATH."sdk/recharge_sdk.php");
require_once(ROOT_PATH."application/constant/Constant.php");
require_once ROOT_PATH. 'application/www/pay/example/log.php';

//初始化日志
$logHandler= new CLogFileHandler("logs/recharge_notify_".date('Y-m-d').'.log');
$log = Log::Init($logHandler, 15);

$data = file_get_contents("php://input");
Log::DEBUG($data);

$data = json_decode($data, true);

$orderData = array();
$outTradeNo = $data["channelOrderId"];

$order = $db->getRow("select * from mb_order where out_trade_no = '$outTradeNo'");
if($order ) {
	Log::DEBUG("mai_status: " . $order["mai_status"]);
	if($order["mai_status"] == "1") {
		echo '{"status":1}';
		exit();
	} else {
		Log::DEBUG("update order data by notify data");
		
		$now = date("Y-m-d H:i:s");
		$sql = " update " . table("order") . " set "
			 . " mai_status = '" . $data["status"] . "',"
			 . " mai_order_id = '" . $data["orderId"] . "',"
			 . " mai_fail_reason = '" . $data["failReason"] . "',"
			 . " mai_price = '" . $data["price"] . "',"
			 . " mai_succ_time = '$now',"
			 . " update_time = '$now' ";
		if($data["status"] == 1) {
			$sql .= " , status = '" . ORDER_STATUS::FINISHED . "' ";
			
			//移动流量可兑换积分
			//读取手机号码地域信息
			$url = "http://122.224.212.160:8980/common/area.action?num=" . $order["phone"];
			$mobileData = file_get_contents($url);
			$mobileData = json_decode($mobileData, true);
			
			if($mobileData["data"]["opCode"] == "0") {
				$userId = $db->getOne("select id from " . table("user") . " where openid = '" . $order["openid"] . "'");
				$wtExchangeData = $db->getRow("select * from " . table("wt_exchange_history") . " where user_id = '$userId' ");
				
				if($wtExchangeData) {
					$wtExchangeTempData["amount"] = $wtExchangeData["amount"] + $order["mb_value"];
					$wtExchangeTempData["update_time"] = $now;
					
					$db->update("wt_exchange_history", $wtExchangeTempData, " and id = " .$wtExchangeData["id"]);
				} else {
					$wtExchangeTempData["amount"] = $order["mb_value"];
					$wtExchangeTempData["exchange_amount"] = 0;
					$wtExchangeTempData["user_id"] = $userId;
					$wtExchangeTempData["insert_time"] = $now;
					$wtExchangeTempData["update_time"] = $now;
					$db->insert("wt_exchange_history", $wtExchangeTempData);
				}
			}
		}
		
		$sql .= " where out_trade_no = '$outTradeNo' ";
		Log::DEBUG("update sql: $sql");
		
		$db->query($sql);
	}
}


?>